package com.study.utils;

import cn.hutool.core.lang.WeightRandom;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.study.configuer.SpringContextHolder;

/**
 * @author ：ihao ∶）
 * @date ：Created in 2021-03-08 14:37
 */

public class ServerProbe {

    private static String[] SERVER_IPS;
    private static String PROBE_MAPPING;

    public static void initParam() {
        if (SERVER_IPS == null) {
            String serverIpsStr = SpringContextHolder.getEnvironmentProperty("server.ips");
            if (serverIpsStr != null) {
                SERVER_IPS = serverIpsStr.split(",");
            }
        }
        if (PROBE_MAPPING == null) {
            PROBE_MAPPING = SpringContextHolder.getEnvironmentProperty("server.probeMapping");
        }
    }

    /**
     * 探测返回
     * @return 成功
     */
    public static String pointProbeReturn() {
        return "success";
    }

    /**
     * 探测服务器点
     * @return 服务器正常可访问ip
     */
    public static String serverPointProbe() {
        initParam();
        WeightRandom<String> weightRandom = new WeightRandom<>();
        for (String serverIp : SERVER_IPS) {
            weightRandom.add(serverIp, 33);
        }
        String serverIp = weightRandom.next();

        HttpResponse execute = HttpUtil.createGet(serverIp + PROBE_MAPPING).setReadTimeout(10000).setConnectionTimeout(10000).execute();
        if (execute != null && execute.getStatus() == 200) {
            return serverIp;
        }
        return serverPointProbe();
    }
}
